package com.hyc.serviceCenter;

import com.alibaba.nacos.api.naming.listener.Event;
import com.alibaba.nacos.api.naming.listener.EventListener;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.alibaba.nacos.client.naming.listener.NamingChangeEvent;
import com.hyc.cache.ServiceCache;
import com.hyc.constant.NacosConstant;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 冷环渊
 * @date 2025/6/11 18:51
 * @description ServiceChangeListener
 */
public class ServiceChangeListener implements EventListener {
    private ServiceCache serviceCache;

    public ServiceChangeListener(ServiceCache serviceCache) {
        this.serviceCache = serviceCache;
    }

    @Override
    public void onEvent(Event event) {
        if (event instanceof NamingChangeEvent) {
            NamingChangeEvent namingChangeEvent = (NamingChangeEvent) event;
            String serviceName = namingChangeEvent.getServiceName();

            if (NacosConstant.RPC_GROUP_NAME.equals(namingChangeEvent.getGroupName())) {
                List<String> old = serviceCache.getCacheList(serviceName);
                if (namingChangeEvent.isAdded()) {
                    List<String> addIps = namingChangeEvent.getAddedInstances().stream()
                            .filter(Instance::isHealthy)
                            .map(Instance::toInetAddr)
                            .collect(Collectors.toList());
                    serviceCache.addServiceToCacheMap(serviceName, addIps);
                }
                if (namingChangeEvent.isModified()) {
                    List<String> modified = namingChangeEvent.getModifiedInstances()
                            .stream()
                            .filter(Instance::isHealthy)
                            .map(Instance::toInetAddr)
                            .collect(Collectors.toList());
                    serviceCache.updateCacheMap(serviceName, old, modified);
                }
                if (namingChangeEvent.isRemoved()) {
                    List<String> removeList = namingChangeEvent.getRemovedInstances()
                            .stream()
                            .filter(Instance::isHealthy)
                            .map(Instance::toInetAddr)
                            .collect(Collectors.toList());
                    serviceCache.deleteCacheNode(serviceName, removeList);
                }
            }
        }

    }
}
